//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.wsd.smartcarwasher.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wsd.smartcarwasher.constans.Constant;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.domain.*;
import com.wsd.smartcarwasher.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WxService {
    private static final Logger logger = LoggerFactory.getLogger(WxService.class);
    @Resource
    private RedisService redisService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private OrderService orderService;
    @Resource
    private PartnerService partnerService;
    @Resource
    private StatisticService statisticService;
    @Resource
    private SysDicService sysDicService;
    @Resource
    private UserFromH5CouponRecordService userFromH5CouponRecordService;
    @Resource
    private OfficialAccountUserService officialAccountUserService;
    public WxService() {
    }

    public ModelMap loginByWeiXin(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=CODE&grant_type=authorization_code";
        url = url.replace("APPID", Constant.APP_ID).replace("SECRET", Constant.APP_SECRET).replace("CODE", code);

        try {
            JSONObject response = WXAuthUtil.doGetJson(url);
            System.out.println("解析登录数据 【"+response.toString()+"】");
            if (response.has("openid")) {
                String openId = response.getString("openid");
                String sessionKey = response.getString("session_key");
                String unionId=null;
                if(!StringUtil.isNullOrEmpty(response.getString("unionid")))
                {
                    unionId=response.getString("unionid");
                }
                this.userInfoService.addUserInfo(openId,unionId);

                String sessionId = StringUtil.getRandomUUID("3rdSessionKey_");
                this.redisService.put(sessionId, openId + "---" + sessionKey, 7200L);
                UserInfo user = this.userInfoService.findByOpenId(openId);
                if (user.getState()==1) {
                    return ReturnUtil.Error("禁止登陆");
                }
                //添加时间
                user.setLastLoginTime(new Date());
                this.userInfoService.updateUser(user);
                if (this.orderService.queryUnPaidOrder(user.getUserId()) != null) {
                    return ReturnUtil.Success(ResultState.NON_PAYMENT.getMsg(), sessionId);
                }

                return ReturnUtil.Success(ResultState.LOGIN_SUCCESS.getMsg(), sessionId);
            }
        } catch (IOException var8) {
            logger.error("fail to get openId:", var8.getMessage());
        }

        return ReturnUtil.Error(ResultState.LOGIN_FAIL.getMsg());
    }

    public ModelMap getWxACode(String sessionId) {
        UserInfo userInfo = this.getUserInfoBySessionId(sessionId);
        if (userInfo != null) {
            String fileName = "wxCode_" + userInfo.getUserId() + ".jpeg";
            //之前是ｏｐｅｎｉｄ　
            String wxCodeUrl = this.getWxACodeFromWx(userInfo.getUserId(), fileName, "pages/index/index");
            if (!StringUtils.isBlank(wxCodeUrl)) {
                userInfo.setWxCodeUrl(wxCodeUrl);
                int resultNum = this.userInfoService.updateUserWxCodeUrl(userInfo);
                if (resultNum != 1) {
                    logger.error("更新用户二维码链接失败");
                }
                String backGroudUrl = sysDicService.getByCode(1003).get(0).getValue();
                String wxCodeBuff= "wxCodeBuff" + userInfo.getUserId() + ".jpg";

                PictureUtil tt = new PictureUtil();
                BufferedImage b = tt.loadImageLocal(Constant.USE_DIR+"wxCode_" + userInfo.getUserId() + ".jpeg");
                BufferedImage d = tt.loadImageLocal(Constant.USE_DIR+backGroudUrl.substring(backGroudUrl.lastIndexOf("/")+1));
                tt.writeImageLocal(Constant.USE_DIR+wxCodeBuff, tt.modifyImagetogeter(b, d));
                //Map<String,Object> msg = new HashMap<>();
                //msg.put("wxCodeUrl","https://mwxc.rungyun.cn:8091/"+wxCodeBuff);
                //msg.put("backUrl","https://mwxc.rungyun.cn:8091/car-wash.e401d259.jpg");
                return ReturnUtil.Success(ResultState.GET_WX_CODE_SUCCESS.getMsg(), Constant.DOMAIN+wxCodeBuff);
            }
        }

        return ReturnUtil.Error(ResultState.GET_WX_CODE_FAIL.getMsg());
    }





    public String getOpenId(String sessionId) {
        //logger.info("sessionId ==== " + sessionId);
        if (StringUtils.isBlank(sessionId)) {
            throw new UnauthenticatedException();
        } else {
            String sessionValue = (String)this.redisService.get(sessionId);
            //logger.info("sessionValue ==== " + sessionValue);
            if (StringUtils.isBlank(sessionValue)) {
                throw new LockedAccountException();
            } else {
                return sessionValue.split("---")[0];
            }
        }
    }

    private String getAccessToken() {
        String accessToken = null;

        /*try {
            accessToken = (String)this.redisService.get("ACCESS_TOKEN");
        } catch (Exception var3) {
            logger.error("catch error when get accessToken from redis", var3);
        }

        if (!StringUtil.isEmpty(accessToken)) {
            String[] tempArray = accessToken.split(":");
            if (!StringUtil.isEmpty(tempArray[0]) && !StringUtil.isEmpty(tempArray[1]) && Long.valueOf(tempArray[1]) * 1000L > System.currentTimeMillis() + 30000L) {
                return tempArray[0];
            }
        }*/

        return this.getAccessTokenFromWeixin();
    }

    private String getAccessTokenFromWeixin() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
        url = url.replace("APPID", Constant.APP_ID).replace("SECRET", Constant.APP_SECRET);
        String accessToken = null;

        try {
            JSONObject response = WXAuthUtil.doGetJson(url);
            if (response.has("access_token")) {
                accessToken = response.getString("access_token");
                int expires = response.getInt("expires_in");
                long expiresTime = System.currentTimeMillis() + (long)(expires * 1000);
                this.redisService.put("ACCESS_TOKEN", accessToken + ":" + expiresTime, (long)expires);
            }
        } catch (Exception var7) {
            logger.error("fail to get AccessToken:", var7);
        }

        return accessToken;
    }

    public UserInfo getUserInfoBySessionId(String sessionId) {
        String openId = this.getOpenId(sessionId);
        return this.userInfoService.findByOpenId(openId);
    }

    String getWxACodeFromWx(String scene, String fileName, String page) {
        String wxCodeUrl = null;
        InputStream inputStream = null;
        String accessToken = this.getAccessToken();
        if (StringUtils.isBlank(accessToken)) {
            return null;
        } else {
            Map<String, Object> param = new HashMap();
            param.put("width", 400);
            param.put("auto_color", true);
            param.put("scene", scene);
            if (StringUtils.isNotBlank(page)) {
                param.put("page", page);
            }

            try {
                CloseableHttpClient httpClient = HttpClientBuilder.create().build();
                HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
                httpPost.addHeader("Content-Type", "application/json");
                String body = JSON.toJSONString(param);
                StringEntity entity = new StringEntity(body);
                entity.setContentType("image/png");
                httpPost.setEntity(entity);
                HttpResponse response = httpClient.execute(httpPost);
                inputStream = response.getEntity().getContent();
                if (response.getStatusLine().getStatusCode() == 200) {
                    //File file = FileUtil.createFile("/usr/local/smartwash/uploadFile/" + fileName);
                    File file = FileUtil.createFile(System.getProperty("user.dir")+ File.separator+"smartwashImages"+File.separator + fileName);
                    this.saveFileToLocal(inputStream, file);
                    //wxCodeUrl = "https://www.snail-tech.cn/uploadFile/" + fileName;
                    wxCodeUrl = Constant.DOMAIN+ fileName;
                }

                logger.info(String.format("response $s code = %s , entity size = %s", response.toString(), response.getStatusLine().getStatusCode(), response.getEntity().getContentLength()));
            } catch (IOException var22) {
                logger.error("生成微信小程序码", var22);
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException var21) {
                        logger.error("生成小程序码--关闭输入流异常", var21);
                    }
                }

            }

            return wxCodeUrl;
        }
    }

    private void saveFileToLocal(InputStream inputStream, File file) {
        FileOutputStream outputStream = null;

        try {
            outputStream = new FileOutputStream(file);
            byte[] buf = new byte[1024];

            int len;
            while((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }

            outputStream.flush();
        } catch (IOException var14) {
            logger.error("保存小程序码到服务器失败", var14);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException var13) {
                    logger.error("生成小程序码--关闭输出流异常", var13);
                }
            }

        }

    }

    public ModelMap partnerLogin(String code) {
        String openId = this.getOpenIdAndAuthAccessToken(code);
        if (StringUtils.isBlank(openId)) {
            return ReturnUtil.Error(ResultState.LOGIN_FAIL.getMsg());
        } else {
            String sessionId = StringUtil.getRandomUUID("3rdSessionKey_");
            this.redisService.put(sessionId, openId, 7200L);
            Map<String, Object> result = new HashMap();
            result.put("sessionId", sessionId);
            Partner partner = this.partnerService.getPartnerByOpenId(openId);
            if (partner != null) {
                result.put("partner", partner);
                result.put("statistic", this.statisticService.getStatistics(partner));
                return ReturnUtil.Success(ResultState.LOGIN_SUCCESS.getMsg(), result);
            } else {
                return ReturnUtil.Success(ResultState.NO_BIND_PARTNER.getMsg(), result);
            }
        }
    }

    public String getOpenIdAndAuthAccessToken(String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        url = url.replace("APPID", Constant.OFFICIAL_APP_ID).replace("SECRET", Constant.OFFICIAL_APP_SECRET).replace("CODE", code);
        String openId = null;

        try {
            JSONObject response = WXAuthUtil.doGetJson(url);
            System.out.println(response);
            if (response.has("access_token")) {
                String accessToken = response.getString("access_token");
                openId = response.getString("openid");
                String refreshToken = response.getString("refresh_token");
                int expires = response.getInt("expires_in");
                long expiresTime = System.currentTimeMillis() + (long)(expires * 1000);
                this.redisService.put(openId, accessToken + ":" + expiresTime + ":" + refreshToken, (long)expires);
            }
        } catch (IOException var10) {
            logger.error("fail to get oauth2:", var10.getMessage());
        }


        return openId;
    }

//    public static void main(String[] args) {
//        Date date = DateUtil.stringToDate("2019-07-29 00:13:09", DateUtil.ymdhms);
//        //System.out.println(date.getTime());
//    }



    //=======================================new  lyj ==============================

    /**
     * 根据sessionid 获取session_key
     */

    public ModelMap getSession_key(String  code){
        JSONObject response =null;
       try{

           String url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=CODE&grant_type=authorization_code";
           url = url.replace("APPID", Constant.APP_ID).replace("SECRET", Constant.APP_SECRET).replace("CODE", code);
           try {
                response = WXAuthUtil.doGetJson(url);
                System.out.println("解析登录数据 【"+response.toString()+"】");
               if (response.has("openid")) {
                   String openId = response.getString("openid");
                   String sessionKey = response.getString("session_key");
                   String sessionId = StringUtil.getRandomUUID("3rdSessionKey_");
                   this.redisService.put(sessionId, openId + "---" + sessionKey, 7200L);
                   //UserInfo user = this.userInfoService.findByOpenId(openId);
                   //if (this.orderService.queryUnPaidOrder(user.getUserId()) != null) {
                   //    return ReturnUtil.Success(ResultState.NON_PAYMENT.getMsg(), sessionKey);
                   //}
                   return ReturnUtil.Success("获取sessionkey 成功", sessionId);
               }
           } catch (IOException var8) {
               logger.error("fail to get openId:", var8.getMessage());
           }
       }catch (Exception e){
            logger.error(e.getMessage());
       }
        return ReturnUtil.Error ("获取sessionkey 失败",response.toString());
    }



    /**
     * 一建登录 并获取用户微信绑定的手机号
     * @param session_key
     * @param encryptedData
     * @param iv
     * @return
     */
    public ModelMap loginByWeiXinGetMobel(String session_key, String encryptedData, String iv,String aUserid) {
        try {
            String [] parm =redisService.get(session_key).toString().split("---");
            //解密手机号
            String  mNumber =WXAuthUtil.decrypt(parm[1],iv,encryptedData);
            String  phoneNumber = new JSONObject(mNumber).getString("phoneNumber");
            //mNumber.put("sessionId",sessionId);
            UserInfo user = this.userInfoService.findByOpenId(parm[0]);
           /* if(null == user){
                UserInfo userInfo  = new UserInfo();
                userInfo.setOpenid(parm[0]);
                userInfo.setMobile(phoneNumber);
                userInfo.setFromId(null==aUserid?"":aUserid);
                userInfo.setRegisterTime(new Date());
                this.userInfoService.addUserInfoLyj(user);
            }else */
//            if(StringUtils.isEmpty(user.getMobile()))
//            {
//                this.tellMachineNewUserRegistion(user.getUserId(),phoneNumber);
//            }
           if(null != user && null == user.getMobile()) {
               user.setMobile(phoneNumber);
               try {
                   UserFromH5CouponRecord userFromH5CouponRecord = userFromH5CouponRecordService.selectH5CouponByMobile(phoneNumber);
                   if (!StringUtil.isNullOrEmpty(userFromH5CouponRecord)) {
                       user.setUserId(userFromH5CouponRecord.getUserid());
                   }
               } catch (Exception e) {
                   logger.info("H5表单存取用户失败");
                   e.printStackTrace();
               }
               try {
                   if(!StringUtil.isNullOrEmpty(user.getUnionId()))
                   {
                       //先关注公众号的情况
                       OfficialAccountUser officialAccountUser=this.officialAccountUserService.selectUserByUnionId(user.getUnionId());
                       if(!StringUtil.isNullOrEmpty(officialAccountUser))
                       {
                           user.setUserId(officialAccountUser.getUserid());
                       }
                   }
               } catch (Exception e)
               {
                   logger.info("查取用户userId失败");
                   e.printStackTrace();
               }

            }
           if(aUserid!=null && user.getFromId()==null && !aUserid.equals(user.getUserId())){
               UserInfo userA = this.userInfoService.findById(aUserid);
               if(userA!=null){
                   user.setFromId(aUserid);
                   //给用户添加优惠卷
                   this.userInfoService.addUserInfoLyj(user);
               }
           }
            this.userInfoService.updateUserMobileByOpenid(user);
            return ReturnUtil.Success("获取手机号成功", mNumber);
        } catch (Exception var8) {
            logger.error("fail to get getPhoneNumber:", var8.getMessage());
            return ReturnUtil.Error("获取手机号异常",var8.getMessage());
        }

    }

    //************************20201107**********************************
    /**
     * 新用户注册申请通知
     * @param userId
     * @param moblie
     */

    public void tellMachineNewUserRegistion(String userId,String moblie)
    {
        Map<String, String> map=new HashMap<>();
        map.put("userId",userId);
        map.put("mobile",moblie);
        String result = null;
        try {
            String url="http://127.0.0.1:5000/gongzhu/songquan";
            url= url.replaceAll(" ", "%20");
            result = HttpClientUtil.doPost(url, map);
            logger.info("发送新用户注册申请成功"+result);
        }catch (Exception e)
        {
            logger.info("发送新用户注册申请失败"+e.getMessage());
            logger.info("发送新用户注册申请失败"+result);
        }
    }
    public static void main(String[] args) {
        Map<String, String> map=new HashMap<>();
        map.put("userId","uiuuy3");
        map.put("mobile","13387238721");
        System.out.println(JSON.toJSONString(map));
    }
}



/*
package com.wsd.smartcarwasher.service;

import com.alibaba.fastjson.JSON;
import com.wsd.smartcarwasher.constans.Constant;
import com.wsd.smartcarwasher.constans.Global;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.domain.Partner;
import com.wsd.smartcarwasher.domain.UserInfo;
import com.wsd.smartcarwasher.util.FileUtil;
import com.wsd.smartcarwasher.util.ReturnUtil;
import com.wsd.smartcarwasher.util.StringUtil;
import com.wsd.smartcarwasher.util.WXAuthUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class WxService {
    private static final Logger logger = LoggerFactory.getLogger(WxService.class);

    @Resource
    private RedisService redisService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private OrderService orderService;

    @Resource
    private PartnerService partnerService;

    @Resource
    private StatisticService statisticService;

    */
/**
     * 用户微信登录
     *
     * @param code 用户微信登录零时凭证
     * @return 用户信息
     *//*

    public ModelMap loginByWeiXin(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=CODE&grant_type=authorization_code";
        url = url.replace("APPID", Constant.APP_ID).replace("SECRET", Constant.APP_SECRET).replace("CODE", code);

        try {
            JSONObject response = WXAuthUtil.doGetJson(url);
            if (response.has("openid")) {
                String openId = response.getString("openid");
                String sessionKey = response.getString("session_key");
                //String unionId = response.getString("unionId");
                userInfoService.addUserInfo(openId);

                String sessionId = StringUtil.getRandomUUID(Global.SESSIONID_PREFIX);
                redisService.put(sessionId, openId + "---" + sessionKey, 7200);

                UserInfo user = userInfoService.findByOpenId(openId);

                if (orderService.queryUnPaidOrder(user.getUserId()) != null) {
                    return ReturnUtil.Success(ResultState.NON_PAYMENT.getMsg(), sessionId);
                }
                return ReturnUtil.Success(ResultState.LOGIN_SUCCESS.getMsg(), sessionId);
            }
        } catch (IOException e) {
            logger.error("fail to get openId:", e.getMessage());
        }
        return ReturnUtil.Error(ResultState.LOGIN_FAIL.getMsg());
    }

    */
/**
     * 用户获取微信小程序码
     *
     * @param sessionId 小程序sessionId
     * @return 返回用户小程序码
     *//*

    public ModelMap getWxACode(String sessionId) {
        UserInfo userInfo = getUserInfoBySessionId(sessionId);
        if (userInfo != null) {
            String fileName = Global.FILE_NAME_PREFIX_WX_CODE + userInfo.getUsername() + Global.FILE_NAME_FORMAT_JPEG;
            String wxCodeUrl = getWxACodeFromWx(userInfo.getOpenid(), fileName, null);
            if (!StringUtils.isBlank(wxCodeUrl)) {
                userInfo.setWxCodeUrl(wxCodeUrl);
                int resultNum = userInfoService.updateUserWxCodeUrl(userInfo);
                if (resultNum != 1) {
                    logger.error("更新用户二维码链接失败");
                }
                return ReturnUtil.Success(ResultState.GET_WX_CODE_SUCCESS.getMsg(), wxCodeUrl);
            }
        }
        return ReturnUtil.Error(ResultState.GET_WX_CODE_FAIL.getMsg());
    }

    public String getOpenId(String sessionId) {
        logger.info("sessionId ==== " + sessionId);
        if (StringUtils.isBlank(sessionId)) {
            throw new UnauthenticatedException();
        }
        String sessionValue = (String) redisService.get(sessionId);
        logger.info("sessionValue ==== " + sessionValue);
        if (StringUtils.isBlank(sessionValue)) {
            throw new LockedAccountException();
        }
        return sessionValue.split("---")[0];
    }

    private String getAccessToken() {
        //从缓存中获取accessToken
        String accessToken = (String)redisService.get(Global.ACCESS_TOKEN);
        //如果缓存不存在，或者accessToken距离过期时间不足30分钟，则重新获取accessToken
        if (!StringUtil.isEmpty(accessToken)) {
            String[] tempArray = accessToken.split(":");
            if (!StringUtil.isEmpty(tempArray[0]) && !StringUtil.isEmpty(tempArray[1])
                    && (Long.valueOf(tempArray[1]) * 1000 > System.currentTimeMillis() + 30 * 1000)) {
                return tempArray[0];
            }
        }
        return getAccessTokenFromWeixin();
    }

    //调用微信接口获取项目AccessToken
    private String getAccessTokenFromWeixin() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
        url = url.replace("APPID", Constant.APP_ID).replace("SECRET", Constant.APP_SECRET);
        String accessToken = null;
        try {
            JSONObject response = WXAuthUtil.doGetJson(url);
            if (response.has("access_token")) {
                accessToken = response.getString("access_token");
                int expires = response.getInt("expires_in");
                long expiresTime = System.currentTimeMillis() + expires * 1000;
                redisService.put(Global.ACCESS_TOKEN, accessToken + ":" + expiresTime, expires);
            }
        } catch (IOException e) {
            logger.error("fail to get AccessToken:", e.getMessage());
        }
        return accessToken;
    }

    public UserInfo getUserInfoBySessionId(String sessionId) {
        String openId = getOpenId(sessionId);
        return userInfoService.findByOpenId(openId);
    }

    //获取微信小程序码并保存到本地
    public String getWxACodeFromWx(String scene, String fileName, String page) {
        String wxCodeUrl = null;
        RestTemplateBuilder builder = new RestTemplateBuilder();
        RestTemplate rest = builder.build();
        InputStream inputStream = null;
        String accessToken = getAccessToken();
        if (StringUtils.isBlank(accessToken)) {
            return null;
        }

        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
        Map<String, Object> param = new HashMap<>();
        param.put("width", 430);
        param.put("auto_color", true);
        param.put("scene", scene);
        if (StringUtils.isNotBlank(page)) {
            param.put("page", page);
        }

        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.set(HttpHeaders.CONTENT_TYPE,MediaType.IMAGE_JPEG_VALUE);
        HttpEntity requestEntity = new HttpEntity<>(JSON.toJSONString(param), headers);
        try {
            ResponseEntity<Object> entity = rest.exchange(url, HttpMethod.POST, requestEntity, Object.class);
            HttpHeaders responseHeaders = entity.getHeaders();
            if (responseHeaders.containsKey("Content-Type")) {
                List<String> contentTypes = responseHeaders.get("Content-Type");
                if (contentTypes.get(0).contains("application/json;")) {
                    Map responseData = (LinkedHashMap) entity.getBody();
                    if (responseData.containsKey("errcode")) {
                        Integer errcode = (Integer) responseData.get("errcode");
                        String errmsg = (String) responseData.get("errmsg");
                        logger.error("生成微信小程序码失败，errcode：" +  errcode + ", errmsg：" + errmsg + "; scene：" + scene + "; page：" + page);
                    }
                    return null;
                }
            } else {
                byte[] result = (byte[]) entity.getBody();
                inputStream = new ByteArrayInputStream(result);
                File file = FileUtil.createFile(Constant.FILE_PATH_PREFIX + fileName);
                saveFileToLocal(inputStream, file);
                wxCodeUrl = Constant.DOMAIN + fileName;
            }
        } catch (IOException e) {
            logger.error("生成微信小程序码", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error("生成小程序码--关闭输入流异常", e);
                }
            }

        }
        return wxCodeUrl;
    }

    //保存二维码到本地
    private void saveFileToLocal(InputStream inputStream, File file) {
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            int len;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();
        } catch (IOException e) {
            logger.error("保存小程序码到服务器失败", e);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    logger.error("生成小程序码--关闭输出流异常", e);
                }
            }
        }
    }

    public ModelMap partnerLogin(String code) {
        String openId = getOpenIdAndAuthAccessToken(code);
        if (StringUtils.isBlank(openId)) {
            return ReturnUtil.Error(ResultState.LOGIN_FAIL.getMsg());
        }
        String sessionId = StringUtil.getRandomUUID(Global.SESSIONID_PREFIX);
        redisService.put(sessionId, openId, 7200);

        Map<String, Object> result = new HashMap<>();
        result.put("sessionId", sessionId);
        Partner partner = partnerService.getPartnerByOpenId(openId);
        if (partner != null) {
            result.put("partner", partner);
            result.put("statistic", statisticService.getStatistics(partner));
        } else {
            return ReturnUtil.Success(ResultState.NO_BIND_PARTNER.getMsg(), result);
        }
        return ReturnUtil.Success(ResultState.LOGIN_SUCCESS.getMsg(), result);
    }

    public String getOpenIdAndAuthAccessToken(String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        url = url.replace("APPID", Constant.OFFICIAL_APP_ID)
                .replace("SECRET", Constant.OFFICIAL_APP_SECRET)
                .replace("CODE", code);
        String openId = null;
        try {
            JSONObject response = WXAuthUtil.doGetJson(url);
            if (response.has("access_token")) {
                String accessToken = response.getString("access_token");
                openId = response.getString("openid");
                String refreshToken = response.getString("refresh_token");
                int expires = response.getInt("expires_in");
                long expiresTime = System.currentTimeMillis() + expires * 1000;
                redisService.put(openId, accessToken + ":" + expiresTime + ":" + refreshToken, expires);
            }
        } catch (IOException e) {
            logger.error("fail to get oauth2:", e.getMessage());
        }
        return openId;
    }

}
*/
